package com.bvr;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class BidsActivity extends ListActivity {

	private ProgressDialog m_ProgressDialog = null;
	private ArrayList<BidObject> m_bids = null;
	private BidObjectAdapter m_adapter;
	private Runnable viewBids;

	// AlertDialog alertPaging;
	private static CharSequence[] itemsParent;

	private static Integer UserID = 0;
	private static String RANGE = "1-10";
	private static Integer totalRecords;
	private static Integer recordsPerPage;

	private static String URL = "";
	private static String METHOD_NAME = "";
	private static String NAMESPACE = "";
	private static String SOAP_ACTION = "";

	private TextView lblNoBid;

	// private Button btnPaging;
	// private TextView lblPaging;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bids);

		setVariables();

		m_bids = new ArrayList<BidObject>();
		this.m_adapter = new BidObjectAdapter(this, R.layout.bid_row, m_bids);
		setListAdapter(this.m_adapter);

		viewBids = new Runnable() {
			@Override
			public void run() {
				getBids();
			}
		};
		Thread thread = new Thread(null, viewBids, "MagentoBackground");
		thread.start();
		m_ProgressDialog = ProgressDialog.show(BidsActivity.this,
				"Please wait...", "Retrieving data ...", true);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		// Get the item that was clicked
		//Object o = this.getListAdapter().getItem(position);

		BidObject bid = m_bids.get(position);

		Intent bidActivityIntent = new Intent(v.getContext(),
				BidActivty.class);	
		
		BidActivty.objBid = bid;		
		startActivityForResult(bidActivityIntent, 0);
	}
	
	private void setVariables() {
		lblNoBid = (TextView) findViewById(R.id.noBid);
		// lblPaging = (TextView) findViewById(R.id.propertyPaging);

		// btnPaging = (Button) findViewById(R.id.btnPaging);
		// btnPaging.setOnClickListener(pagingListener);

		// UserID =
		// MyApp appState = ((MyApp)getApplicationContext());
		// UserID = appState.getUserId();
		SharedPreferences appSettings = getSharedPreferences(
				"BVRAppPreferences", MODE_PRIVATE);
		String ownerID = appSettings.getString("ownerID", "0");
		UserID = Integer.parseInt(ownerID);
		// UserID = 723; // Integer.parseInt(ownerID);

		recordsPerPage = Integer.parseInt(getString(R.string.records_per_page));
		//totalRecords = Integer.parseInt(appSettings.getString("bidsCount",
		//		"0"));

		RANGE = "1-" + getString(R.string.records_per_page);
		URL = getString(R.string.url_bids);
		METHOD_NAME = getString(R.string.method_name_bids);
		NAMESPACE = getString(R.string.namespace_bids);
		SOAP_ACTION = getString(R.string.soap_action_bids);

		// setPagingAlert();
	}

	private void getBids() {
		try {
			m_bids = new ArrayList<BidObject>();

			ParseWebService();
			Log.i("ARRAY", "" + m_bids.size());
		} catch (Exception e) {
			Log.e("BACKGROUND_PROC", e.getMessage());
		}
		runOnUiThread(returnRes);
	}

	private Runnable returnRes = new Runnable() {
		@Override
		public void run() {
			if (m_bids != null && m_bids.size() > 0) {
				m_adapter.notifyDataSetChanged();
				for (int i = 0; i < m_bids.size(); i++)
					m_adapter.add(m_bids.get(i));
			} else {
				lblNoBid.setText(getText(R.string.main_no_items));
			}
			m_ProgressDialog.dismiss();
			m_adapter.notifyDataSetChanged();
			// lblPaging.setText(RANGE);
		}
	};

	private void ParseWebService() throws IOException, XmlPullParserException,
			JSONException {

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		request.addProperty("ownerID", UserID);
		request.addProperty("range", RANGE);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;

		envelope.implicitTypes = true;
		envelope.encodingStyle = "utf-8";
		envelope.enc = SoapSerializationEnvelope.ENC2001;
		envelope.xsd = SoapEnvelope.XSD;
		envelope.xsi = SoapEnvelope.XSI;

		envelope.setOutputSoapObject(request);
		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		envelope.addMapping(NAMESPACE, "Properties",
				new PropertyObject().getClass());
		androidHttpTransport.call(SOAP_ACTION, envelope);
		androidHttpTransport
				.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

		androidHttpTransport.debug = true;
		SoapObject soapresultmsg = (SoapObject) envelope.getResponse();
		SoapObject recordsArray = (SoapObject) soapresultmsg.getProperty(0);
		int recordCount = recordsArray.getPropertyCount();
		// debugDisplay("Records ka Count hai : " +
		// Integer.toString(recordCount));
		m_bids= new ArrayList<BidObject>();
		try {
			for (int i = 0; i < recordCount; i++) {
				BidObject bid = new BidObject();
				Ksoap2ResultParser.parseBusinessObject(recordsArray
						.getProperty(i).toString(), bid);
				m_bids.add(bid);
			}

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
